<template>
  <div class="mail-forgot-page">
    <!-- 顶部导航 -->
    <header class="top-nav">
      <div class="nav-container">
        <div class="nav-left">
          <img
            src="@/assets/images/logo.png"
            alt="贵港文旅+"
            class="nav-logo"
          />
          <div class="brand-wrapper">
            <span class="brand-name">贵港文旅+</span>
            <span class="brand-pinyin">GUIGANGWENLV+</span>
          </div>
          <span class="divider">|</span>
          <span class="nav-title">你的专业文旅助手</span>
        </div>
        <div class="nav-right">
          <a href="/" class="nav-link">贵港文旅首页</a>
          <a href="#" class="nav-link">手机App下载</a>
          <a href="#" class="nav-link">电脑客户端下载</a>
          <a href="/merchant/apply" class="nav-link">商家入驻</a>
          <router-link to="/help/guide" class="nav-link">帮助</router-link>
          <a href="#" class="nav-link">反馈</a>
          <router-link to="/login" class="nav-link login-link"
            >去登录</router-link
          >
        </div>
      </div>
    </header>

    <!-- 主要内容区 -->
    <main class="main-content">
      <div class="forgot-container">
        <div class="forgot-box">
          <h2 class="forgot-title">找回密码</h2>
          <p class="forgot-subtitle">通过手机号或邮箱找回密码</p>

          <div class="verify-type-selector" v-if="!isVerified">
            <div
              class="verify-option"
              :class="{ active: verifyType === 'phone' }"
              @click="handleSelectVerifyType('phone')"
            >
              <el-icon><Phone /></el-icon>
              <span>手机号验证</span>
            </div>
            <div
              class="verify-option"
              :class="{ active: verifyType === 'email' }"
              @click="handleSelectVerifyType('email')"
            >
              <el-icon><Message /></el-icon>
              <span>邮箱验证</span>
            </div>
          </div>

          <!-- 添加联系方式输入 -->
          <div v-if="verifyType && !codeSent" class="contact-input">
            <el-form-item :prop="verifyType">
              <el-input
                v-if="verifyType === 'phone'"
                v-model="form.phone"
                placeholder="请输入手机号"
                :prefix-icon="Phone"
                clearable
              />
              <el-input
                v-else
                v-model="form.email"
                placeholder="请输入邮箱"
                :prefix-icon="Message"
                clearable
              />
            </el-form-item>
            <el-button
              type="primary"
              class="send-code-btn"
              :loading="loading"
              @click="handleSendCode"
            >
              发送验证码
            </el-button>
          </div>

          <div class="verification-code-input" v-if="codeSent && !isVerified">
            <input
              v-for="(digit, index) in 6"
              :key="index"
              :ref="
                (el) => {
                  if (el) codeInputs[index] = el;
                }
              "
              v-model="verificationDigits[index]"
              type="text"
              maxlength="1"
              class="code-digit"
              @input="handleCodeInput(index)"
              @keydown.delete="handleCodeDelete(index)"
              @keydown.left="focusInput(index - 1)"
              @keydown.right="focusInput(index + 1)"
            />
          </div>

          <div class="verification-status" v-if="!isVerified">
            <span v-if="!verifyType" class="select-tip"> 请选择验证方式 </span>
            <span v-else-if="timer" class="countdown-tip">
              {{ countdown }}秒后可重新选择验证方式
            </span>
            <span v-else-if="codeSent" class="verification-tip">
              验证码已发送至{{ verifyType === "phone" ? "手机" : "邮箱" }}
            </span>
          </div>

          <div v-if="isVerified && !resetSuccess" class="password-section">
            <el-form-item prop="password">
              <el-input
                v-model="form.password"
                type="password"
                placeholder="请设置新密码"
                :prefix-icon="Lock"
                show-password
              />
              <div class="password-strength" v-if="form.password">
                <div class="strength-indicators">
                  <div
                    v-for="(level, index) in strengthLevels"
                    :key="index"
                    class="strength-indicator"
                    :class="[
                      `strength-${level}`,
                      { active: passwordStrength >= index + 1 },
                    ]"
                  />
                </div>
                <span
                  class="strength-text"
                  :class="`text-${strengthLevels[passwordStrength - 1]}`"
                >
                  密码强度: {{ strengthTexts[passwordStrength - 1] }}
                </span>
              </div>
            </el-form-item>

            <el-form-item prop="confirmPassword">
              <el-input
                v-model="form.confirmPassword"
                type="password"
                placeholder="请确认新密码"
                :prefix-icon="Lock"
                show-password
              />
            </el-form-item>

            <el-button
              type="primary"
              class="submit-btn"
              :loading="loading"
              @click="handleResetPassword"
            >
              重置密码
            </el-button>
          </div>

          <div v-if="resetSuccess" class="success-message">
            <el-icon class="success-icon"><CircleCheck /></el-icon>
            <h3>密码重置成功</h3>
            <p>您的密码已经重置成功，请使用新密码登录</p>
            <el-button
              type="primary"
              class="submit-btn"
              @click="handleComplete"
            >
              返回登录
            </el-button>
          </div>

          <div class="form-footer">
            <router-link to="/login" class="login-link">返回登录</router-link>
          </div>
        </div>
      </div>
    </main>

    <!-- 页脚 -->
    <footer class="page-footer">
      <div class="footer-info">
        <span>贵港文旅版权所有 ©2024</span>
        <a href="#" class="footer-link">ICP备案 桂B2-20240101</a>
        <a href="#" class="footer-link">
          <img
            src="@/assets/images/police-badge.png"
            class="police-badge"
            alt="警徽"
          />
          桂公网安备 45010602006299号
        </a>
        <a href="#" class="footer-link">增值电信业务经营许可证 桂B2-20240101</a>
      </div>
    </footer>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onUnmounted } from "vue";
import {
  User,
  Lock,
  Phone,
  Message,
  CircleCheck,
} from "@element-plus/icons-vue";
import { useRouter } from "vue-router";
import { ElMessage } from "element-plus";
import { sendResetCode, verifyResetCode, resetPassword } from "@/api/auth";

const router = useRouter();
const loading = ref(false);
const timer = ref(null);
const countdown = ref(0);
const verifyType = ref("");
const codeInputs = ref([]);
const verificationDigits = ref(["", "", "", "", "", ""]);
const codeSent = ref(false);
const isVerified = ref(false);
const resetSuccess = ref(false);

const strengthLevels = ["weak", "weak", "medium", "strong"];
const strengthTexts = ["非常弱", "弱", "中", "强"];

const form = reactive({
  phone: "",
  email: "",
  password: "",
  confirmPassword: "",
  verificationCode: "",
  verifyToken: "",
});

// 密码强度计算
const passwordStrength = computed(() => {
  const { password } = form;
  if (!password) return 0;

  let strength = 0;
  const rules = {
    length: { score: 2, test: () => password.length >= 8 },
    lowercase: { score: 1, test: () => /[a-z]/.test(password) },
    uppercase: { score: 1, test: () => /[A-Z]/.test(password) },
    numbers: { score: 1, test: () => /\d/.test(password) },
    symbols: { score: 2, test: () => /[!@#$%^&*(),.?":{}|<>]/.test(password) },
    middleNumbersSymbols: {
      score: 2,
      test: () => /[0-9!@#$%^&*(),.?":{}|<>]/.test(password.slice(1, -1)),
    },
    requirements: {
      score: 2,
      test: () => {
        let count = 0;
        if (/[A-Z]/.test(password)) count++;
        if (/[a-z]/.test(password)) count++;
        if (/[0-9]/.test(password)) count++;
        if (/[^A-Za-z0-9]/.test(password)) count++;
        return count >= 3;
      },
    },
  };

  Object.values(rules).forEach((rule) => {
    if (rule.test()) {
      strength += rule.score;
    }
  });

  const repeatingChars = password.match(/(.)\1{2,}/g);
  if (repeatingChars) {
    strength = Math.max(0, strength - repeatingChars.length);
  }

  if (strength >= 9) return 3; // 强
  if (strength >= 6) return 2; // 中
  if (strength >= 3) return 1; // 弱
  return 0; // 非常弱
});

// 添加表单验证规则
const rules = {
  phone: [
    { required: true, message: "请输入手机号", trigger: "blur" },
    {
      pattern: /^1[3-9]\d{9}$/,
      message: "请输入正确的手机号",
      trigger: "blur",
    },
  ],
  email: [
    { required: true, message: "请输入邮箱", trigger: "blur" },
    { type: "email", message: "请输入正确的邮箱地址", trigger: "blur" },
  ],
};

const handleSelectVerifyType = async (type) => {
  if (timer.value) {
    ElMessage.warning(`请等待${countdown.value}秒后再切换验证方式`);
    return;
  }

  if (type === verifyType.value && timer.value) {
    return;
  }

  verifyType.value = type;
  verificationDigits.value = ["", "", "", "", "", ""];
  form.verificationCode = "";
  isVerified.value = false;
  codeSent.value = false;
};

const handleCodeInput = async (index) => {
  const digit = verificationDigits.value[index];
  if (digit) {
    if (!/^\d$/.test(digit)) {
      verificationDigits.value[index] = "";
      return;
    }
    if (index < 5) {
      focusInput(index + 1);
    } else {
      form.verificationCode = verificationDigits.value.join("");
      await verifyCode();
    }
  }
};

const focusInput = (index) => {
  if (index >= 0 && index < 6) {
    codeInputs.value[index]?.focus();
  }
};

const handleCodeDelete = (index) => {
  if (!verificationDigits.value[index] && index > 0) {
    verificationDigits.value[index - 1] = "";
    focusInput(index - 1);
  }
};

const verifyCode = async () => {
  try {
    if (form.verificationCode.length !== 6) return;

    loading.value = true;
    const response = await verifyResetCode({
      type: verifyType.value,
      target: form[verifyType.value],
      code: form.verificationCode
    });

    // 添加日志查看响应
    console.log('验证响应:', response);
    
    // 检查响应格式
    if (response && response.data) {
      isVerified.value = true;
      // 可能需要调整获取 token 的方式
      form.verifyToken = response.data.verifyToken || response.data;
      ElMessage.success("验证码验证成功");
    } else {
      console.error('响应格式不正确:', response);
      ElMessage.error("验证失败，响应格式不正确");
    }
  } catch (error) {
    console.error('验证出错:', error);
    isVerified.value = false;
    ElMessage.error(error.message || "验证码错误，请重新输入");
    verificationDigits.value = ["", "", "", "", "", ""];
    form.verificationCode = "";
    focusInput(0);
  } finally {
    loading.value = false;
  }
};

const handleSendCode = async () => {
  try {
    // 验证输入的联系方式
    if (!form[verifyType.value]) {
      ElMessage.warning(
        `请输入${verifyType.value === "phone" ? "手机号" : "邮箱"}`,
      );
      return;
    }

    // 验证格式
    if (verifyType.value === "phone" && !/^1[3-9]\d{9}$/.test(form.phone)) {
      ElMessage.warning("请输入正确的手机号");
      return;
    }
    if (
      verifyType.value === "email" &&
      !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(form.email)
    ) {
      ElMessage.warning("请输入正确的邮箱地址");
      return;
    }

    loading.value = true;
    await sendResetCode({
      type: verifyType.value,
      target: form[verifyType.value]
    });

    codeSent.value = true;
    ElMessage.success(
      `验证码已发送至${verifyType.value === "phone" ? "手机" : "邮箱"}`,
    );
    countdown.value = 60;
    timer.value = setInterval(() => {
      countdown.value--;
      if (countdown.value <= 0) {
        clearInterval(timer.value);
        timer.value = null;
      }
    }, 1000);
  } catch (error) {
    ElMessage.error(error.message || "发送验证码失败");
  } finally {
    loading.value = false;
  }
};

const handleResetPassword = async () => {
  if (!form.password) {
    ElMessage.warning("请设置新密码");
    return;
  }
  if (form.password !== form.confirmPassword) {
    ElMessage.warning("两次输入的密码不一致");
    return;
  }
  try {
    loading.value = true;
    await resetPassword({
      verifyToken: form.verifyToken,
      password: form.password
    });
    resetSuccess.value = true;
  } catch (error) {
    ElMessage.error("重置密码失败，请重试");
  } finally {
    loading.value = false;
  }
};

const handleComplete = () => {
  router.push("/login");
};

onUnmounted(() => {
  if (timer.value) {
    clearInterval(timer.value);
    timer.value = null;
  }
});
</script>

<style lang="scss" scoped>
.mail-forgot-page {
  @apply min-h-screen flex flex-col relative;
  background: url("@/assets/images/register-bg.jpg") center/cover fixed
    no-repeat;

  &::before {
    content: "";
    @apply fixed inset-0 z-0;
    background: linear-gradient(
      to bottom,
      rgba(255, 255, 255, 0.9) 0%,
      rgba(255, 255, 255, 0) 64px,
      rgba(255, 255, 255, 0) calc(100% - 64px),
      rgba(255, 255, 255, 0.9) 100%
    );

    .dark & {
      background: linear-gradient(
        to bottom,
        rgba(17, 24, 39, 0.9) 0%,
        rgba(17, 24, 39, 0.4) 64px,
        rgba(17, 24, 39, 0.4) calc(100% - 64px),
        rgba(17, 24, 39, 0.9) 100%
      );
    }
    pointer-events: none;
  }

  .top-nav {
    @apply w-full fixed top-0 left-0 z-50;

    .nav-container {
      @apply max-w-7xl mx-auto h-16 flex items-center justify-between;
      padding-left: 16px;
      padding-right: 8px;

      .nav-left {
        @apply flex items-center;

        .nav-logo {
          @apply h-14 mr-2;

          .dark & {
            filter: brightness(1.2)
              drop-shadow(0 0 8px rgba(255, 255, 255, 0.3));
          }
        }

        .brand-wrapper {
          @apply flex flex-col justify-center;

          .brand-name {
            @apply text-2xl font-bold text-gray-800 dark:text-gray-100 leading-6;
          }

          .brand-pinyin {
            @apply text-[8px] text-gray-500 dark:text-gray-400 mt-0.5;
          }
        }

        .divider {
          @apply mx-3 text-gray-300 dark:text-gray-600 text-xl;
        }

        .nav-title {
          @apply text-gray-700 dark:text-gray-200 text-lg font-medium;
        }
      }

      .nav-right {
        @apply flex items-center;
        gap: 24px;

        .nav-link {
          @apply text-sm text-gray-600 dark:text-gray-300 hover:text-[#2e74e5] dark:hover:text-[#60a5fa] transition-colors;
        }
      }
    }
  }

  .main-content {
    @apply flex-1 flex items-center justify-center relative z-10;
    padding: 80px 0;
    margin-top: 64px;

    .forgot-container {
      @apply w-[480px];

      .forgot-box {
        @apply bg-white/95 dark:bg-gray-900/95 backdrop-blur-sm rounded-2xl shadow-xl dark:shadow-2xl p-8;

        .forgot-title {
          @apply text-2xl font-bold text-center mb-2;
          background: linear-gradient(to right, #2e74e5, #2361c5);
          -webkit-background-clip: text;
          -webkit-text-fill-color: transparent;

          .dark & {
            background: linear-gradient(to right, #60a5fa, #3b82f6);
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
          }
        }

        .forgot-subtitle {
          @apply text-base text-gray-600 dark:text-gray-300 text-center mb-8;
        }

        .verify-type-selector {
          @apply flex gap-5 mb-8;

          .verify-option {
            @apply flex-1 p-5 rounded-xl border-2 border-gray-200 dark:border-gray-700 cursor-pointer
                   flex flex-col items-center gap-3 transition-all duration-300
                   hover:shadow-sm relative overflow-hidden;

            &::before {
              content: "";
              @apply absolute inset-0 bg-gradient-to-br from-blue-50 dark:from-blue-900/20 to-transparent opacity-0 transition-opacity duration-300;
            }

            .el-icon {
              @apply text-3xl text-gray-400 dark:text-gray-500 transition-colors duration-300;
            }

            span {
              @apply text-base text-gray-600 dark:text-gray-300 transition-colors duration-300;
            }

            &:hover {
              @apply border-blue-200 dark:border-blue-700;

              &::before {
                @apply opacity-100;
              }

              .el-icon {
                @apply text-blue-500 dark:text-blue-400;
              }
            }

            &.active {
              @apply border-blue-500 dark:border-blue-400 shadow-sm;

              &::before {
                @apply opacity-100;
              }

              .el-icon {
                @apply text-blue-500 dark:text-blue-400;
              }

              span {
                @apply text-blue-500 dark:text-blue-400;
              }
            }
          }
        }

        .contact-input {
          @apply mb-6;
          max-width: 380px;
          margin-left: auto;
          margin-right: auto;

          .el-form-item {
            @apply mb-4;

            :deep(.el-input__wrapper) {
              @apply h-11 rounded-2xl bg-white dark:bg-gray-800;
              box-shadow: none !important;
              border: 1px solid #d1d5db !important;

              &:hover {
                border-color: #9ca3af !important;
              }

              &.is-focus {
                border-color: #2e74e5 !important;
                box-shadow: 0 0 0 4px rgba(37, 99, 235, 0.1) !important;

                .dark & {
                  border-color: #3b82f6 !important;
                  box-shadow: 0 0 0 4px rgba(37, 99, 235, 0.2) !important;
                }
              }

              .el-input__inner {
                @apply text-base text-gray-900 dark:text-gray-100;
                &::placeholder {
                  @apply text-gray-400 dark:text-gray-500;
                }
              }

              .el-input__prefix {
                @apply mr-2;
                .el-icon {
                  @apply text-xl text-gray-400 dark:text-gray-500;
                }
              }
            }
          }

          .send-code-btn {
            @apply w-full h-11 text-base rounded-2xl shadow-sm;
            background: linear-gradient(to right, #2e74e5, #2361c5);

            .dark & {
              background: linear-gradient(to right, #3b82f6, #2563eb);
            }

            &:hover {
              background: linear-gradient(to right, #2361c5, #1d4ed8);

              .dark & {
                background: linear-gradient(to right, #60a5fa, #3b82f6);
              }
            }
          }
        }

        .verification-code-input {
          @apply flex gap-4 justify-center mb-5;

          .code-digit {
            @apply w-14 h-14 rounded-lg border border-gray-200 dark:border-gray-700 text-center text-2xl
                   focus:border-blue-500 dark:focus:border-blue-400 focus:outline-none transition-all duration-300
                   bg-white/80 dark:bg-gray-800/80 backdrop-blur-sm shadow-sm text-gray-900 dark:text-gray-100;

            &:focus {
              @apply shadow-md ring-2 ring-blue-100 dark:ring-blue-900;
            }

            &:hover {
              @apply border-gray-300 dark:border-gray-600 shadow-md;
            }
          }
        }

        .verification-status {
          @apply text-base text-center py-3 px-6 rounded-full bg-gray-50 dark:bg-gray-800 mb-8;

          .select-tip {
            @apply text-gray-400 dark:text-gray-500;
          }

          .countdown-tip {
            @apply text-orange-500 dark:text-orange-400 font-medium;
          }

          .verification-tip {
            @apply text-green-500 dark:text-green-400;
          }
        }

        .password-section {
          @apply mt-8;

          .el-form-item {
            @apply mb-6;

            :deep(.el-input__wrapper) {
              @apply h-12 rounded-xl bg-white dark:bg-gray-800;
              box-shadow: none !important;
              border: 1px solid #d1d5db !important;

              &:hover {
                border-color: #9ca3af !important;
              }

              &.is-focus {
                border-color: #2e74e5 !important;
                box-shadow: 0 0 0 4px rgba(37, 99, 235, 0.1) !important;

                .dark & {
                  border-color: #3b82f6 !important;
                  box-shadow: 0 0 0 4px rgba(37, 99, 235, 0.2) !important;
                }
              }

              .el-input__inner {
                @apply text-base text-gray-900 dark:text-gray-100;
                &::placeholder {
                  @apply text-gray-400 dark:text-gray-500;
                }
              }

              .el-input__prefix {
                @apply mr-2;
                .el-icon {
                  @apply text-xl text-gray-400 dark:text-gray-500;
                }
              }
            }
          }
        }

        .password-strength {
          @apply flex items-center gap-3 mt-2;

          .strength-indicators {
            @apply flex gap-2;

            .strength-indicator {
              @apply w-12 h-1.5 rounded-full transition-all duration-300;
              background-color: #e5e7eb;

              &.active {
                &.strength-weak {
                  @apply bg-red-500 dark:bg-red-400;
                }
                &.strength-medium {
                  @apply bg-yellow-500 dark:bg-yellow-400;
                }
                &.strength-strong {
                  @apply bg-green-500 dark:bg-green-400;
                }
              }
            }
          }

          .strength-text {
            @apply text-sm;

            &.text-weak {
              @apply text-red-500 dark:text-red-400;
            }
            &.text-medium {
              @apply text-yellow-500 dark:text-yellow-400;
            }
            &.text-strong {
              @apply text-green-500 dark:text-green-400;
            }
          }
        }

        .success-message {
          @apply text-center py-8;

          .success-icon {
            @apply text-6xl text-green-500 dark:text-green-400 mb-4;
          }

          h3 {
            @apply text-xl font-bold text-gray-800 dark:text-gray-100 mb-2;
          }

          p {
            @apply text-gray-600 dark:text-gray-300 mb-8;
          }
        }

        .submit-btn {
          @apply w-full h-11 text-base rounded-2xl shadow-sm;
          max-width: 380px;
          margin-left: auto;
          margin-right: auto;
          display: block;
          background: linear-gradient(to right, #2e74e5, #2361c5);

          .dark & {
            background: linear-gradient(to right, #3b82f6, #2563eb);
          }

          &:hover {
            background: linear-gradient(to right, #2361c5, #1d4ed8);

            .dark & {
              background: linear-gradient(to right, #60a5fa, #3b82f6);
            }
          }
        }

        .form-footer {
          @apply flex justify-center mt-4;

          .login-link {
            @apply text-base text-[#2e74e5] dark:text-[#60a5fa] hover:text-[#2361c5] dark:hover:text-[#3b82f6] font-medium;
          }
        }
      }
    }
  }

  .page-footer {
    @apply w-full py-6 text-center fixed bottom-0 left-0 z-50;
    background: transparent;

    .footer-info {
      @apply text-sm text-gray-500 dark:text-gray-400 space-x-4 relative z-10;

      .footer-link {
        @apply text-gray-500 dark:text-gray-400 hover:text-[#2e74e5] dark:hover:text-[#60a5fa] transition-colors;
      }

      .police-badge {
        @apply h-4 inline-block align-middle mr-1;

        .dark & {
          filter: brightness(0.8) contrast(1.2);
        }
      }
    }
  }
}

/* 移动端样式 */
@media screen and (max-width: 768px) {
  .mail-forgot-page {
    .top-nav {
      .nav-container {
        .nav-right {
          display: none;
        }
      }
    }

    .main-content {
      @apply px-4;
      margin-top: 0;

      .forgot-container {
        @apply w-full mx-4;
        margin-left: auto;

        .forgot-box {
          @apply p-6;
        }
      }
    }
  }
}
</style>
